package com.shaoshaohuo.app.ui.fragment;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.entity.Baoxian;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.FocusImage;
import com.shaoshaohuo.app.entity.MainEntity;
import com.shaoshaohuo.app.entity.News;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.ui.LoginActivity;
import com.shaoshaohuo.app.ui.WebBrowserActivity;
import com.shaoshaohuo.app.adapter.FaceMarketHeadVpAdapter;
import com.shaoshaohuo.app.ui.ec.MyFragmentActivity;
import com.shaoshaohuo.app.view.CirclePageIndicator;
import com.shaoshaohuo.app.view.MainActionPop;
import com.shaoshaohuo.app.view.MainActionPop.OnSelectItemListener;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.utils.ImageLoadUtil;
import com.shaoshaohuo.app.utils.ToastUtil;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;

/**
 * @ClassName EcMainActivity
 * @author linmu
 * @Decription 未登录首页 @2015-8-28 下午9:40:41
 */
public class LogoutFragment extends Fragment implements OnClickListener {

	private View mContentView;

	private TopbarView mTopbarView;
	private CirclePageIndicator mIndicator;
	private ViewPager mHeaderViewPager;

	private ImageView mShipperText;
	private ImageView mCarText;
	private ImageView mBuyText;
	
	private TextView mLoginText;

	private String mArgument;

	private MainActionPop shipperPop;

	private MainActionPop carPop;

	private MainActionPop buyPop;

	private MainActionPop sellPop;
	public static final String ARGUMENT = "argument";

	public static LogoutFragment newInstance(String argument) {
		Bundle bundle = new Bundle();
		bundle.putString(ARGUMENT, argument);
		LogoutFragment contentFragment = new LogoutFragment();
		contentFragment.setArguments(bundle);
		return contentFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle bundle = getArguments();
		if (bundle != null)
			mArgument = bundle.getString(ARGUMENT);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.fragment_logout1, null);

			initView();
			setUpView();
			requestMainImages();
		} else {
			ViewGroup parent = (ViewGroup) mContentView.getParent();
			if (parent != null) {
				parent.removeView(mContentView);
			}
		}
		return mContentView;
	}

	private void initView() {
		mTopbarView = (TopbarView) mContentView.findViewById(R.id.topbar);
		mTopbarView.setCenterText(R.string.app_name);
//		mTopbarView.setLeftImage(R.drawable.navbar_menu);
//		mTopbarView.setLeftClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				((MainTabActivity) getActivity()).toggle();
//			}
//		});
		// mTopbarView.setRightImage(R.drawable.navbar_msg);
		// mTopbarView.setRightClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if (AccountManager.isLogin()) {
		// Intent intent = new Intent(getActivity(),
		// MessageCenterActivity.class);
		// getActivity().startActivity(intent);
		// } else {
		// Intent intent = new Intent(getActivity(), LoginActivity.class);
		// getActivity().startActivity(intent);
		// }
		// }
		// });

		mHeaderViewPager = (ViewPager) mContentView.findViewById(R.id.viewpager_main1_header);
		mIndicator = (CirclePageIndicator) mContentView.findViewById(R.id.cpi_face_viewpager);

		mShipperText = (ImageView) mContentView.findViewById(R.id.textview_huozhu);
		mCarText = (ImageView) mContentView.findViewById(R.id.textview_car);
		mBuyText = (ImageView) mContentView.findViewById(R.id.textview_buy);
		
		mLoginText = (TextView) mContentView.findViewById(R.id.textview_login);
	}

	private void setUpView() {
		mShipperText.setOnClickListener(this);
		mCarText.setOnClickListener(this);
		mBuyText.setOnClickListener(this);
		mLoginText.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_huozhu:
			Intent intent1 = new Intent(getActivity(),MyFragmentActivity.class);
			intent1.putExtra(ExtraName.id, 1);
			getActivity().startActivity(intent1);
//			((MainTabActivity)getActivity()).changeState("1");
//			showShipperDialog();
			break;
		case R.id.textview_car:
			Intent intent2 = new Intent(getActivity(),MyFragmentActivity.class);
			intent2.putExtra(ExtraName.id, 2);
			getActivity().startActivity(intent2);
//			((MainTabActivity)getActivity()).changeState("2");
//			showCarDialog();
			break;
		case R.id.textview_buy:
			Intent intent3 = new Intent(getActivity(),MyFragmentActivity.class);
			intent3.putExtra(ExtraName.id, 3);
			getActivity().startActivity(intent3);
//			((MainTabActivity)getActivity()).changeState("3");
//			showBuyDialog();
			break;
		case R.id.textview_sell:
			Intent intent4 = new Intent(getActivity(),MyFragmentActivity.class);
			intent4.putExtra(ExtraName.id, 3);
			getActivity().startActivity(intent4);
//			((MainTabActivity)getActivity()).changeState("3");
//			showSellDialog();
			break;
		case R.id.textview_login:
			Intent intent5 = new Intent(getActivity(),LoginActivity.class);
			getActivity().startActivity(intent5);
//			((MainTabActivity)getActivity()).changeState("3");
//			showSellDialog();
			break;
		}
	}

	protected void showShipperDialog() {
		if (shipperPop != null && shipperPop.isShowing()) {
			return;
		}

		mShipperText.setSelected(true);

		if (shipperPop == null) {
			shipperPop = new MainActionPop(getActivity(), new String[] { "我要发货", "我要找车" });
			shipperPop.setOnSelectItemListener(new OnSelectItemListener() {

				@Override
				public void onSelect(int pos) {
				}
			});
			shipperPop.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mShipperText.setSelected(false);
				}
			});
		}

		shipperPop.showLocation(mShipperText);
	}

	protected void showCarDialog() {
		if (carPop != null && carPop.isShowing()) {
			return;
		}
		mCarText.setSelected(true);
		if (carPop == null) {
			carPop = new MainActionPop(getActivity(), new String[] { "我要找货", "周边路况", "工具箱" });
			carPop.setOnSelectItemListener(new OnSelectItemListener() {

				@Override
				public void onSelect(int pos) {
				}
			});
			carPop.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mCarText.setSelected(false);
				}
			});
		}

		carPop.showLocation(mCarText);
	}

	protected void showBuyDialog() {
		if (buyPop != null && buyPop.isShowing()) {
			return;
		}
		mBuyText.setSelected(true);
		if (buyPop == null) {
			buyPop = new MainActionPop(getActivity(), new String[] { "查看商机", "发布信息", "寻找供应商" });
			buyPop.setOnSelectItemListener(new OnSelectItemListener() {

				@Override
				public void onSelect(int pos) {
				}
			});
			buyPop.setOnDismissListener(new OnDismissListener() {

				@Override
				public void onDismiss() {
					mBuyText.setSelected(false);
				}
			});
		}

		buyPop.showLocation(mBuyText);
	}

	private void requestMainImages() {
		RequestService.getInstance().mainIndex(getActivity(), 1 + "", MainEntity.class, new RequestListener() {

			@Override
			public void onSuccess(int requestCode, BaseEntity resultData) {

				if (resultData.isOk()) {
					MainEntity result = (MainEntity) resultData;
					setMainImages(result.getData().getFocus());
					setNews(result.getData().getNews());
					saveBx(result.getData().getBx());
				} else {
					ToastUtil.toast(resultData.getMsg());
				}
			}

			@Override
			public void onFailed(int requestCode, Exception error, String msg) {
				try {
					ToastUtil.toast(R.string.please_check_network);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	protected void saveBx(Baoxian bx) {
		AccountManager.saveBaoxian(bx);
	}

	protected void setNews(List<News> news) {
	}

	protected void setMainImages(List<FocusImage> result) {

		this.pagerSize = result.size();

		HeaderVpAdapter adapter = new HeaderVpAdapter(getActivity(), result, 1, result.size());
		mHeaderViewPager.setAdapter(adapter);
		mIndicator.setViewPager(mHeaderViewPager);
		mIndicator.notifyDataSetChanged();
		startPagerTask();
	}

	private class HeaderVpAdapter extends FaceMarketHeadVpAdapter<FocusImage> {

		public HeaderVpAdapter(Context context, List<FocusImage> array, int previewCount, int maxListSize) {
			super(context, array, previewCount, maxListSize);
		}

		@Override
		public Object getView(ViewGroup container, final FocusImage data, int position) {

			View view = View.inflate(mContext, R.layout.view_main1_header_item, null);
			ImageView imageView = (ImageView) view.findViewById(R.id.imageView_main1_header_item);
			switch (position) {
			default:
				break;
			}

			// LoadUtils.getInstance().loadImage(imageView, Data.getBigimg(),
			// new
			// LoadImageListener() {
			//
			// @Override
			// public void onStart(ImageView arg0, String arg1) {
			// // TODO Auto-generated method stub
			//
			// }
			//
			// @Override
			// public void onResult(ImageView imageView, String arg1, boolean
			// isLoadSuccess, Bitmap
			// arg3) {
			// // if(isLoadSuccess){
			// // imageView.setBackgroundDrawable(new BitmapDrawable(arg3));
			// // }
			// }
			//
			// @Override
			// public void onProcessChange(ImageView arg0, String arg1, long
			// arg2, long arg3) {
			// // TODO Auto-generated method stub
			//
			// }
			// });

			ImageLoader.getInstance().displayImage(data.getBigimg(), imageView, ImageLoadUtil.build);

			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// Toast.makeText(mContext, "header", 0).show();

				}
			});

			container.addView(view);

			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (!TextUtils.isEmpty(data.getUrl())) {
						Intent intent = new Intent(getActivity(), WebBrowserActivity.class);
						intent.putExtra(WebBrowserActivity.TITLE, data.getTitle());
						intent.putExtra(WebBrowserActivity.URL, data.getUrl());
						getActivity().startActivity(intent);
					}
				}
			});

			return view;
		}

	}

	private ScheduledExecutorService scheduledExecutorService;
	private int pagerSize;
	public int currentItem;
	private static final int delayTime = 3;

	private void startPagerTask() {
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 每隔2秒钟切换一张图片
		scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), delayTime, delayTime, TimeUnit.SECONDS);
		mHeaderViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				currentItem = arg0;
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}

	private class ViewPagerTask implements Runnable {

		@Override
		public void run() {
			currentItem = (currentItem + 1) % pagerSize;
			handler.obtainMessage().sendToTarget();
		}
	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			mHeaderViewPager.setCurrentItem(currentItem);
		}
	};
}
